package com.lfs.aspects;

import com.lfs.common.constant.CommonConstants;
import com.lfs.common.utils.StringUtils;
import com.lfs.interfaces.dto.ResultReturn;
import com.lfs.model.vo.AgentAccess;
import com.lfs.service.AppManagerService;
import com.lfs.util.DESUtils;
import com.lfs.util.DESUtilsForC;
import com.google.common.base.Preconditions;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
public class ParameterAspect {

    private final Logger log = LoggerFactory.getLogger(ParameterAspect.class);

    @Resource
    private AppManagerService appManagerService;

    @Around("execution(@com.lfs.annotations.ParameterValid * *(..)) or execution(* *(@com.lfs.annotations.ParameterValid (*), ..))")
    public Object checkParameter(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();
        Preconditions.checkArgument((args.length != 0), "checkParameter校验失败");
        Preconditions.checkArgument((args[0] != null), "Parameter参数不允许为空");
        Preconditions.checkArgument((args[0] instanceof Parameter), "Parameter参数类型异常");
        Parameter parameter = (Parameter) args[0];
        // 参数解密
        AgentAccess agentAccess = appManagerService.queryAppKeyByAppId(parameter.getAppId());
        String param = null;
        try {
            if (agentAccess == null) {
                return new ResultReturn<>().setStatus(CommonConstants.RESP_CHARGE_EXCETION).setMsg("获取用户秘钥失败!").setData(null);
            } else {
                if(agentAccess.getAppType().equals(CommonConstants.SECURITY_FOR_C)){
                    param = decryptForC(parameter.getParam(), agentAccess.getAppKey());
                }else {
                    param = decrypt(parameter.getParam(), agentAccess.getAppKey());
                }
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return new ResultReturn<>().setStatus(CommonConstants.RESP_CHARGE_EXCETION).setMsg("参数解密失败,请检查提交的加密参数!").setData(null);
        }
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(param), "参数解密失败:" + parameter.getParam());
        } catch (Exception e) {
            log.error("参数解密异常!", e.getMessage());
            return new ResultReturn<>().setStatus(CommonConstants.RESP_CHARGE_EXCETION).setMsg("提交参数有误").setData(null);

        }
        parameter.setParam(param);
        log.info("参数解密成功:" + parameter.getParam());
        args[0] = parameter;
        try {
            return point.proceed(args);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return new ResultReturn<>().setStatus(CommonConstants.RESP_CHARGE_EXCETION).setMsg("提交参数有误").setData(null);
        } finally {
//            long end = System.currentTimeMillis();
//            long duration = end - start;
//            apiLog.setDuration(duration);
        }
    }

    private String decrypt(String parameter, String key) {
        Preconditions.checkArgument(StringUtils.isNotBlank(key), "应用未开通权限，请联系客服人员");
        try {
            return DESUtils.decrypt(parameter, key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private String decryptForC(String parameter, String key) {
        Preconditions.checkArgument(StringUtils.isNotBlank(key), "应用未开通权限，请联系客服人员");
        try {
            return DESUtilsForC.decrypt(parameter, key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
